package server.mapper;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import server.*;
import server.container.Context;
import server.container.Engine;
import server.container.Host;
import server.container.Wrapper;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Mapper {

    private static Server server = Catalina.server;

    public static void map(Request request){
        List<Service> serviceList = server.getServiceList();
        serviceList.forEach(service -> {
            Map<String, Host> hostMap = service.getEngine().getHostList().stream().collect(Collectors.toMap(Host::getName, Function.identity()));
            Host host = hostMap.get(request.getHostName());
            request.getMappingData().setHost(host);
            if (Objects.isNull(host)){
                return;
            }
            Context mappedContext = null;
            for (Context context : host.getContextList()) {
                if (request.getUrl().startsWith(context.getPath())){
                    mappedContext = context;
                    break;
                }
            }
            request.getMappingData().setContext(mappedContext);
            if (Objects.isNull(mappedContext)){
                return;
            }
            String servletPath = request.getUrl().replaceFirst(mappedContext.getPath(), "");
            int index;
            if ((index = servletPath.indexOf("?")) > 0){
                servletPath = servletPath.substring(0,index);
            }
            Wrapper mappedWrapper = null;
            for (Wrapper wrapper : request.getMappingData().getContext().getWrapperList()) {
                if (wrapper.getUrl().equals(servletPath)){
                    mappedWrapper = wrapper;
                    break;
                }
            }
            request.getMappingData().setWrapper(mappedWrapper);
        });
    }
}
